package cn.eshore.bnet.bpm.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.sun.xml.messaging.saaj.util.ByteInputStream;

import cn.eshore.bnet.bpm.dto.ext.CopyOfCustomer;
import cn.eshore.bnet.bpm.dto.ext.CopyOfOffering;
import cn.eshore.bnet.bpm.dto.ext.Customer;

public class XML2Java {

    /**
     * //TODO 添加方法功能描述
     * 
     * @param args
     * @throws JAXBException
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args) throws JAXBException,
            UnsupportedEncodingException {
        java2xml2();
    }

    private static void xml2java() throws JAXBException {
        JAXBContext j = JAXBContext.newInstance("cn.eshore.bnet.bpm.dto");
        Unmarshaller unmarshaller = j.createUnmarshaller();
        File f = new File("Customer.xml");
        Object object = unmarshaller.unmarshal(f);
        System.out.println(object.getClass().getName());
    }

    public static void java2xml() throws JAXBException {
        JAXBContext j = JAXBContext.newInstance("cn.eshore.bnet.bpm.dto");
        Marshaller marshaller = j.createMarshaller();
        Customer createCustomer = new Customer();

        createCustomer.setBnetId("dfsefs");
        marshaller.marshal(createCustomer, System.out);
    }

    public static void java2xml2() throws JAXBException,
            UnsupportedEncodingException {
        JAXBContext j = JAXBContext.newInstance(
                CopyOfCustomer.class,
                CopyOfOffering.class);
        Marshaller marshaller = j.createMarshaller();
   //     marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
  //      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        CopyOfCustomer createCustomer = new CopyOfCustomer();
        final CopyOfOffering copyOfOffering = new CopyOfOffering();
        copyOfOffering.setNodeId("eetr");
        createCustomer.getOfferings().add(copyOfOffering);
        createCustomer.setBnetId("dfsefs");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        marshaller.marshal(createCustomer, outputStream);
        String str = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("str:" + str);
        Unmarshaller unmarshaller = j.createUnmarshaller();
        byte[] bytes = str.getBytes();
        CopyOfCustomer object = (CopyOfCustomer) unmarshaller
                .unmarshal(new ByteInputStream(bytes, bytes.length));
        System.out.println(object.getOfferings().size());

    }

}
